/*
 * FPContextListener.java
 * 
 * Copyright 2008 David D. Emory
 * 
 * This file is part of Five Points. See <http://www.fpdev.org> for
 * additional information regarding the project.
 * 
 * Five Points is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Five Points is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Five Points.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.fpdev.apps.web.servlets;

import java.io.File;
import java.rmi.Naming;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.fpdev.apps.web.FPServer;

/**
 *
 * @author demory
 */
public class FPContextListener implements ServletContextListener {

  private ServletContext context_;

  public void contextInitialized(ServletContextEvent event) {
    context_ = event.getServletContext();

    try {

      // setup root logger
      Logger rootLogger = Logger.getLogger("");
      Handler[] handlers = rootLogger.getHandlers();
      if (handlers.length > 0 && handlers[0] instanceof ConsoleHandler) {
        rootLogger.removeHandler(handlers[0]);
      }

      // setup server reference
      FPServer server =
              (FPServer) Naming.lookup("//localhost/FPServer");
      context_.setAttribute("FPServer", server);
      
      
      // setup main tomcat logger
      Logger logger = Logger.getLogger("org.fpdev.tomcatLogger");
      // add file handler
      if (logger.getHandlers().length == 0) {
        FileHandler handler = new FileHandler(server.get5PHome() + "server" + File.separator + "logs" + File.separator + "main.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
      }
      
      logger.log(Level.INFO, "context initialized");



    } catch (Exception ex) {
      ex.printStackTrace();
    }

  }

  public void contextDestroyed(ServletContextEvent event) {
  }
}
